//
//  YHMyMerchantViewController.m
//  YHApp
//
//  Created by -- on 2021/6/25.
//

#import "HAAllMerchantVC.h"
#import "HAMerchantCell.h"
#import "HAMerchantDetailsVC.h"
#import "HAMerchantListMo.h"
#import "HAMerchantScreenPopView.h"
#import "HAPolicyListMo.h"

@interface HAAllMerchantVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
/***/
@property (nonatomic, strong) UITextField *seachField;
/***/
@property (nonatomic, strong) NSString *keyword;
/***/
@property (nonatomic, strong) NSString *source_id;
/***/
@property (nonatomic, strong) NSString *start;
/***/
@property (nonatomic, strong) NSString *end;
/***/
@property (nonatomic, strong) NSString *canalsAll;
@property (nonatomic, strong) NSString *canals;
/***/
@property (nonatomic, strong) NSString *policy_id;
/***/
@property (nonatomic, strong) NSString *product_id;
/***/
@property (nonatomic, strong) NSString *state;

/***/
@property (nonatomic, strong) NSMutableArray *policyLists;
/***/
@property (nonatomic, strong) NSMutableArray *termmodLists;
/***/
@property (nonatomic, strong) UILabel *totalLabel;

@end

@implementation HAAllMerchantVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.baseTLabel.text = @"全部商户";

    [self setupUI];
    
    self.canalsAll = @"";
    
    MJRefreshGifHeader *mj_header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header = mj_header;
    
    MJRefreshBackGifFooter *mj_footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(laodMoreData)];
    self.tableView.mj_footer = mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
    
    [self loadTermMods];
    [self loadPolicyItems];
    
    // Do any additional setup after loading the view.
}

-(void)dealloc {
    for (HACanalItemMo *mo in [HASingle single].canalItemArray) {
        mo.isSel = NO;
    }
}


-(void)setupUI {
    
    UIView *seachBgView = [UIView ha_createView];
    seachBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:seachBgView];
    [seachBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.baseNavView.mas_bottom).offset(1);
        make.left.right.mas_equalTo(0);
        make.height.mas_offset(44);
    }];
    
    UIButton *moreBtn = [[UIButton alloc]init];
    [moreBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [moreBtn addTarget:self action:@selector(moreBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [seachBgView addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.centerY.mas_equalTo(0);
        make.width.mas_offset(32);
        make.height.mas_offset(32);
    }];

    UIButton *seachBtn = [[UIButton alloc]init];
    [seachBtn setImage:[UIImage xl_cuttingImageWith:[UIImage imageNamed:@"ha_searchIcon"] toSize:CGSizeMake(22, 22)] forState:UIControlStateNormal];
    [seachBtn addTarget:self action:@selector(seachBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [seachBgView addSubview:seachBtn];
    [seachBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(moreBtn.mas_left).offset(-5);
        make.centerY.mas_equalTo(0);
        make.width.mas_offset(32);
        make.height.mas_offset(32);
    }];

    UITextField *seachField = [[UITextField alloc]init];
    self.seachField = seachField;
    seachField.delegate = self;
    seachField.placeholder = @"请输入名称/编号/机具编号";
    seachField.font = [UIFont systemFontOfSize:18];
    seachField.returnKeyType = UIReturnKeySearch;
    [seachBgView addSubview:seachField];
    [seachField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.equalTo(seachBtn.mas_left).offset(-15);
        make.centerY.mas_equalTo(0);
        make.height.equalTo(@32);
    }];
    
    UIView *totalView = [[UIView alloc] init];
    [self.view addSubview:totalView];
    [totalView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(seachBgView.mas_bottom);
        make.height.mas_offset(40);
    }];
    
    UILabel *totaltitLabel = [UILabel ha_NLabelWithFont:16 textColor:@"#333333" text:@"商户总量" alignment:0];
    [totalView addSubview:totaltitLabel];
    [totaltitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(15);
        make.width.mas_offset(72);
    }];
    
    UILabel *totalConLabel = [UILabel ha_NLabelWithFont:16 textColor:@"#666666" text:@"0" alignment:2];
    self.totalLabel = totalConLabel;
    [totalView addSubview:totalConLabel];
    [totalConLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.right.mas_equalTo(-15);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(totalView.mas_bottom);
        make.bottom.mas_equalTo(0);
    }];
}



#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 66;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HAMerchantCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHMyMerchantCellID"];
    if (!cell) {
        cell = [[HAMerchantCell alloc]initWithStyle:0 reuseIdentifier:@"YHMyMerchantCellID"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HAMerchantListMo *model = self.dataArray[indexPath.row];
    HAMerchantDetailsVC *vc = [[HAMerchantDetailsVC alloc]init];
    vc.customer_id = model.customer_id;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)seachBtnClick {

    self.keyword = self.seachField.text;
    
    [self.tableView.mj_header beginRefreshing];

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [self.view endEditing:YES];
    
    if (textField == self.seachField) {
    
        self.keyword = textField.text;
        
        [self.tableView.mj_header beginRefreshing];
    }

    return YES;
}

-(void)moreBtnClick{
    [self.view endEditing:YES];
    WS(weakSelf)
    HAMerchantScreenPopView *menu = [[HAMerchantScreenPopView alloc]init];
    menu.keyword = self.seachField.text;
    menu.start = self.start;
    menu.end = self.end;
    menu.type = self.source_id;
    menu.state = self.state;
    menu.policyLists = self.policyLists;
    menu.termmodLists = self.termmodLists;
    [menu loadViews];
    [menu show];
    menu.HAMerchantScreenPopViewBlock = ^(NSString * _Nonnull searchText, NSString * _Nonnull start, NSString * _Nonnull end, NSString * _Nonnull typeText, NSString * _Nonnull stateText) {
        weakSelf.keyword = searchText;
        weakSelf.start = start;
        weakSelf.end = end;
        weakSelf.source_id = typeText;
        weakSelf.state = stateText;
        weakSelf.seachField.text = searchText;
        NSString *policy_id = @"";
        for (HAPolicyListMo *mo in weakSelf.policyLists) {
            if (mo.isSel == YES) {
                policy_id = mo.policy_id;
                break;
            }
        }
        weakSelf.policy_id = policy_id;
        NSString *product_id = @"";
        for (HACanalItemMo *mo in weakSelf.termmodLists) {
            if (mo.isSel == YES) {
                product_id = mo.value;
                break;
            }
        }
        weakSelf.product_id = product_id;
        NSString *canals = @"";
        for (HACanalItemMo *mo in [HASingle single].canalItemArray) {
            if (mo.isSel == YES) {
                canals = mo.value;
                break;
            }
        }
        self.canals = canals;
        if ([NSString isEmptyString:self.canals]) {
            weakSelf.canals = weakSelf.canalsAll;
        }
        [weakSelf.tableView.mj_header beginRefreshing];
    };
}


-(void)loadNewData {

    NSDictionary *dict = @{
        @"pageSize":@"10",
        @"page":@"1",
        @"source_id":self.source_id?:@"",
        @"keyword":self.keyword?:@"",
        @"start":self.start?:@"",
        @"end":self.end?:@"",
        @"canals":self.canals?:@"",
        @"policy_id":self.policy_id?:@"",
        @"product_id":self.product_id?:@"",
        @"state":self.state?:@"",
    };
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"customer/lists"];
    request1.requestMethod = SYRequestMethodPOST;
    request1.parms = dict;

    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            
            [self.tableView.mj_header endRefreshing];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                [self.dataArray removeAllObjects];
                if ([[dataModel.data allKeys]containsObject:@"data"]) {
                    NSArray *arr = [HAMerchantListMo mj_objectArrayWithKeyValuesArray:[dataModel.data valueForKey:@"data"]];
                    [self.dataArray addObjectsFromArray:arr];
                }
                if ([[dataModel.data allKeys]containsObject:@"total"]) {
                    self.totalLabel.text = [NSString stringWithFormat:@"%@",dataModel.data[@"total"]];
                }
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            
            [self.tableView reloadData];
            
        }
    }];
    
}

-(void)loadPolicyItems {
    NSDictionary *dict = @{
        @"canal" : @"",
    };
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = @"v1/policy/lists";
    request1.requestMethod = SYRequestMethodGET;
    request1.parms = dict;
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            if (dataModel.code == 1) {
                [self.policyLists removeAllObjects];
                NSArray *array = [HAPolicyListMo mj_objectArrayWithKeyValuesArray:dataModel.data];
                [self.policyLists addObjectsFromArray:array];
            }
        }
    }];
}

-(void)loadTermMods {
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = @"product/items";
    request1.requestMethod = SYRequestMethodGET;
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            if (dataModel.code == 1) {
                [self.termmodLists removeAllObjects];
                NSArray *array = [HACanalItemMo mj_objectArrayWithKeyValuesArray:dataModel.data];
                [self.termmodLists addObjectsFromArray:array];
            }
        }
    }];
}



-(void)laodMoreData {
    
    NSInteger count = ceilf(self.dataArray.count*0.1)+1;
    NSString *pageNo = [NSString stringWithFormat:@"%ld",(long)count];
    
    NSDictionary *dict = @{
        @"pageSize":@"10",
        @"page":pageNo,
        @"source_id":self.source_id?:@"",
        @"keyword":self.keyword?:@"",
        @"start":self.start?:@"",
        @"end":self.end?:@"",
        @"canals":self.canals?:@"",
        @"policy_id":self.policy_id?:@"",
        @"product_id":self.product_id?:@"",
        @"state":self.state?:@"",
    };
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"customer/lists"];
    request1.requestMethod = SYRequestMethodPOST;
    request1.parms = dict;

    [self.tableView.mj_footer beginRefreshing];
    
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            
            [self.tableView.mj_footer endRefreshing];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                if ([[dataModel.data allKeys]containsObject:@"data"]) {
                    NSArray *arr = [HAMerchantListMo mj_objectArrayWithKeyValuesArray:[dataModel.data valueForKey:@"data"]];
                    [self.dataArray addObjectsFromArray:arr];
                }
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            
            [self.tableView reloadData];
        }
    }];
    
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        // 去掉滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.backgroundColor = [UIColor khaBGColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)policyLists
{
    if (!_policyLists) {
        _policyLists = [NSMutableArray array];
    }
    return _policyLists;
}

- (NSMutableArray *)termmodLists
{
    if (!_termmodLists) {
        _termmodLists = [NSMutableArray array];
    }
    return _termmodLists;
}


#pragma mark - 无数据处理 DZNEmptyDataSetSource DZNEmptyDataSetDelegate
//设置title
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"暂无数据~";
    NSDictionary *attributes = @{
        NSFontAttributeName:[UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#999999"]
    };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}


//设置image
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"yh_nodata"];
}


@end





